import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui show Image, ImageByteFormat;
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/custom_tabbar.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';

import 'clipboard.dart';

typedef CallbackImage = void Function(XFile? file);

class ToolsUtils {
  ToolsUtils._();

  static TextEditingController editingController(String content) {
    TextEditingController textEditingController = TextEditingController(text: content);
    textEditingController.value = TextEditingValue(
        text: content,
        selection: TextSelection.fromPosition(
            TextPosition(affinity: TextAffinity.downstream, offset: content.length)));
    return textEditingController;
  }

  static Builder builderLeading({ Color? color }) {
    return Builder(
      builder: (BuildContext context) {
        return IconButton(
          onPressed: () {
            String pre = Get.previousRoute;
            if (pre.isEmpty || pre.trim().isEmpty) {
              /// 返回到首页
              Get.toNamed(RoutePath.home);
              return;
            }
            Get.back();
          },
          icon: Icon(Icons.arrow_back_ios, color: color,),
        );
      },
    );
  }

  static SvgPicture assetImageSvg(
    String assetName, {
    BoxFit fit = BoxFit.cover,
    double? width,
    double? height,
  }) {
    if (!assetName.endsWith('.svg')) {
      assetName = '$assetName.svg';
    }
    return SvgPicture.asset(
      'assets/svg/$assetName',
      width: width,
      height: height,
      fit: fit,
    );
  }

  static SvgPicture urlSvg(String url,
      {double? width, double? height, BoxFit fit = BoxFit.contain}) {
    return SvgPicture.network(url, width: width, height: height, fit: fit);
  }

  static AssetImage assetImageIcon(String assetName) {
    return AssetImage('assets/image/icon/$assetName');
  }

  static Image image(
    String assetName, {
    BoxFit? fit,
    double? width,
    double? height,
  }) {
    return Image.asset(
      'assets/image/$assetName',
      fit: fit,
      width: width,
      height: height,
    );
  }

  static AssetImage assetImage(String assetName) {
    return AssetImage(
      'assets/image/$assetName',
    );
  }

  static String getImgPath(String name, {String format = 'png'}) {
    return 'assets/image/$name.$format';
  }

  static ClientTabBar getClientTabBar(
    List<String> tabs,
    TabController controller, {
    Color backgroundColor = Colors.transparent,
    ValueChanged<int>? onTap,
    TabBarIndicatorSize indicatorSize = TabBarIndicatorSize.label,
    bool isScrollable = true,
    double indicatorMinWidth = 36,
    double indicatorWeight = 2,
    String indicatorColor = ColorsUtils.colorF048,
    String labelColor = ColorsUtils.colorF048,
    TextStyle? labelStyle,
    String unselectedLabelColor = ColorsUtils.color6666,
    TextStyle? unselectedLabelStyle,
  }) {
    return ClientTabBar(
      tabs: tabs.map((e) {
        return Tab(
          text: e,
        );
      }).toList(),
      controller: controller,
      indicatorSize: indicatorSize,
      isScrollable: isScrollable,
      padding: EdgeInsets.zero,
      indicator: RRecTabIndicator(
          radius: 1,
          insets: EdgeInsets.only(bottom: 5.w),
          color: ColorsUtils.parseColorFromHexString(indicatorColor)),
      indicatorMinWidth: indicatorMinWidth,
      indicatorWeight: indicatorWeight,
      labelColor: ColorsUtils.parseColorFromHexString(labelColor),
      labelStyle: labelStyle ?? StylesUtils.customTextStyle(fontSize: StylesUtils.defaultFontSize),
      unselectedLabelColor: ColorsUtils.parseColorFromHexString(unselectedLabelColor),
      unselectedLabelStyle: unselectedLabelStyle ??
          StylesUtils.customTextStyle(fontSize: StylesUtils.defaultFontSize),
      backgroundColor: backgroundColor,
      onTap: onTap,
    );
  }

  ///value: 文本内容；fontSize : 文字的大小；fontWeight：文字权重；maxWidth：文本框的最大宽度；maxLines：文本支持最大多少行
  static double calculateTextHeight(BuildContext context, String value, FontWeight fontWeight,
      fontSize, double maxWidth, int maxLines) {
    if (value.isEmpty) {
      return 0.0;
    }
    TextPainter painter = TextPainter(
      locale: Localizations.localeOf(context),
      maxLines: maxLines,
      textDirection: TextDirection.ltr,
      text: TextSpan(
        text: value,
        style: TextStyle(
          fontSize: fontSize,
          fontWeight: fontWeight,
        ),
      ),
    );
    painter.layout(maxWidth: maxWidth);
    return painter.width;
  }

  static Future<ByteData?> widgetToImage(Widget widget,
      {Alignment alignment = Alignment.center,
      Size size = const Size(double.maxFinite, double.maxFinite),
      double devicePixelRatio = 1.0,
      double pixelRatio = 1.0}) async {
    RenderRepaintBoundary repaintBoundary = RenderRepaintBoundary();

    RenderView renderView = RenderView(
      child: RenderPositionedBox(alignment: alignment, child: repaintBoundary),
      configuration: ViewConfiguration(
        // size: size,
        devicePixelRatio: devicePixelRatio,
      ),
      view: WidgetsBinding.instance.platformDispatcher.views.first,
      // window: ui.window,
    );

    PipelineOwner pipelineOwner = PipelineOwner();
    pipelineOwner.rootNode = renderView;
    renderView.prepareInitialFrame();

    BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
    RenderObjectToWidgetElement rootElement = RenderObjectToWidgetAdapter(
      container: repaintBoundary,
      child: widget,
    ).attachToRenderTree(buildOwner);
    buildOwner.buildScope(rootElement);
    buildOwner.finalizeTree();

    pipelineOwner.flushLayout();
    pipelineOwner.flushCompositingBits();
    pipelineOwner.flushPaint();

    ui.Image image = await repaintBoundary.toImage(pixelRatio: pixelRatio);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    return byteData;
  }

  static Future<ui.Image> loadImageByProvider(
    ImageProvider provider, {
    ImageConfiguration config = ImageConfiguration.empty,
  }) async {
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调
    ImageStream stream = provider.resolve(config); //获取图片流
    ImageStreamListener listener = ImageStreamListener((ImageInfo frame, bool sync) {
      //监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
    });
    stream.addListener(listener); //添加监听
    stream.removeListener(listener); //移除监听
    return completer.future; //返回
  }

  /// 分享
  static void openShare() {
    Get.bottomSheet(SizedBox(
      height: 280,
      child: Column(
        children: [
          Container(
            height: 40,
            alignment: Alignment.center,
            decoration:
                BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
            child: Text(
              '分享',
              style: StylesUtils.customTextStyle(fontSize: StylesUtils.fontSize16),
            ),
          ),
          Expanded(
              child: Container(
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            padding: const EdgeInsets.only(top: 20),
            child: StaggeredGrid.count(
              crossAxisCount: 3,
              crossAxisSpacing: 10,
              mainAxisSpacing: 30,
              children: [
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3728', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '微信好友',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3729', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '微信朋友圈',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3730', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        'QQ好友',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3740', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        'QQ空间',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3741', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '新浪微博',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                InkWell(
                  onTap: () {
                    ClipboardUtils.copy('text');
                  },
                  child: Column(
                    children: [
                      Center(
                        child: SvgUtils.assetName('u3737', width: 37.w, height: 30.h),
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 10),
                        alignment: Alignment.center,
                        child: Text(
                          '复制链接',
                          style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          )),
          InkWell(
            onTap: Get.back,
            child: Container(
              height: 40,
              alignment: Alignment.center,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
              child: Text('取消',
                  style: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.fontSize16, color: ColorsUtils.color9999)),
            ),
          )
        ],
      ),
    ));
  }

  static Future<List<XFile>> loadGalleryImage() async {
    final ImagePicker picker = ImagePicker();
    return await picker.pickMultiImage();
  }

  /// 拍照
  static Future<XFile?> cameraImage() async {
    final picker = ImagePicker();
    return await picker.pickImage(
      source: ImageSource.camera,
    );
  }

  /// 相册选取
  static Future<XFile?> galleryImage() async {
    final picker = ImagePicker();
    return await picker.pickImage(source: ImageSource.gallery);
  }

  /// 拍照或选取照片
  static void photograph(BuildContext context, {CallbackImage? callback}) {
    showCupertinoModalPopup<void>(
        context: context,
        builder: (BuildContext context) {
          return CupertinoActionSheet(
            actions: [
              CupertinoActionSheetAction(
                isDefaultAction: true,
                isDestructiveAction: true,
                onPressed: () {
                  cameraImage().then((XFile? file) {
                    callback?.call(file);
                  }).catchError((err) {
                    Get.printError(info: 'err = ${err.toString()}');
                  }).whenComplete(() {
                    Navigator.pop(context);
                  });
                },
                child: Text(
                  '拍照',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize18),
                ),
              ),
              CupertinoActionSheetAction(
                isDefaultAction: true,
                isDestructiveAction: true,
                onPressed: () {
                  galleryImage().then((XFile? file) {
                    callback?.call(file);
                    Navigator.pop(context);
                  }, onError: (err) {
                    Navigator.pop(context);
                  });
                },
                child: Text(
                  '从相册选取',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize18),
                ),
              )
            ],
            cancelButton: CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                isDestructiveAction: true,
                child: Text(
                  '取消',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize18),
                )),
          );
        });
  }
}
